package com.weasel.weixin.mp.servlet;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.weasel.weixin.commons.helper.SignatureHelper;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * Created by Dylan on 2015/9/28.
 */
public class BindUserServlet extends WeixinBaseServlet {

    public final static Cache<String,String> userBinder = CacheBuilder.newBuilder().build();


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String openid = (String) request.getSession().getAttribute("openid");
        if(StringUtils.isEmpty(openid)){
            response.getWriter().write("<h1>认证错误！<h1>");
            return;
        }
        userBinder.put(openid,username);

        response.getWriter().write("<h1>认证成功！</h1>");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        String timestamp = request.getParameter("timestamp");
        String signature = request.getParameter("signature");
        String openid = request.getParameter("openid");
        if(!SignatureHelper.check("mytoken",timestamp,openid,signature) || new Date().after(new Date(Long.valueOf(timestamp)))){
            response.getWriter().write("非法请求");
            return;
        }
        session.setAttribute("openid",openid);

        String html = "<html>";
        html+="<div style='width:400px;height:300px;border:1px solid red;text-align:center;padding-top:20px;'>";
        html+="<form action='http://yhwemall.ngrok.jlw365.com/bind_user' method='post'>";
        html+="<table>";
        html+="<tr><td>用户名:<input type='text' name='username'/></tr></td>";
        html+="<tr><td>密码:<input type='password' name='password'/></tr></td>";
        html+="<tr><td><input type='submit' value='认证'/></td></tr>";
        html+="</table>";
        html+="</form>";
        html+="</div>";
        html += "</html>";

        response.getWriter().write(html);
    }

}
